package driver

import (
	"fmt"
	"time"

	"gitee.com/mkwchecking/sr-core/log"
)

type Conn struct {
	Driver    Engine `json:"driver"` // mysql, postgres, sqlite3, sqlserver
	Username  string `json:"username"`
	Password  string `json:"password"`
	Address   string `json:"address"`   // ip:port
	Database  string `json:"database"`  // default database
	Charset   string `json:"charset"`   // default : utf8
	ParseTime bool   `json:"parseTime"` // default: true
	Dsn       string `json:"dsn"`       // custom dsn
}

type Config struct {
	Conn
	Migrate     bool      `json:"migrate"`     // auto migrate
	IdleTimeout int       `json:"idleTimeout"` // idle timeout
	MaxIdle     int       `json:"maxIdle"`     // max idle connections
	Log         *Log      `json:"log"`         // log
	Resolves    []Resolve `json:"resolves"`    // resolve
}

type Log struct {
	Level         log.Level     `json:"level"`         // log level
	TraceKey      string        `json:"traceKey"`      // get trace id from ctx
	SlowThreshold time.Duration `json:"slowThreshold"` // slow threshold (ms)
	Colorful      bool          `json:"colorful"`      // colorful
	CallSkip      int           `json:"callSkip"`      // call skip
}

type Resolve struct {
	Sources      []Conn         `json:"sources"`  // sources
	Replicas     []Conn         `json:"replicas"` // replicas
	Policy       ConnPoolPolicy `json:"policy"`   // random, roundRobin
	TraceResolve bool           `json:"traceResolve"`
	Tables       []any          `json:"tables"` // tables
}

func (c Conn) GetDSN() string {
	if c.Dsn != "" {
		return c.Dsn
	}
	switch c.Driver {
	case MySQL:
		return fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=True&loc=Local", c.Username, c.Password, c.Address, c.Database, c.Charset)
	case Postgres:
		return fmt.Sprintf("postgres://%s:%s@%s/%s", c.Username, c.Password, c.Address, c.Database)
	case SQLite3:
		return c.Address
	default:
		return ""
	}
}
